

package com.hazelcast.jet.json;

import com.fasterxml.jackson.jr.ob.impl.DeferredMap;
import com.hazelcast.jet.impl.serialization.SerializerHookConstants;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Serializer;
import com.hazelcast.nio.serialization.SerializerHook;
import com.hazelcast.nio.serialization.StreamSerializer;

import java.io.IOException;
import java.util.Map;

/**
 * Hazelcast serializer hooks for the classes in the {@code
 * com.hazelcast.jet.json} package. This is not a public-facing API.
 */
class JsonSerializerHooks {

    public static final class DeferredMapHook implements SerializerHook<DeferredMap> {

        @Override
        public Class<DeferredMap> getSerializationType() {
            return DeferredMap.class;
        }

        @Override
        public Serializer createSerializer() {
            return new StreamSerializer<DeferredMap>() {

                @Override
                public int getTypeId() {
                    return SerializerHookConstants.DEFERRED_MAP;
                }

                @Override
                public void write(ObjectDataOutput out, DeferredMap deferredMap) throws IOException {
                    out.writeInt(deferredMap.size());
                    for (Map.Entry<String, Object> entry : deferredMap.entrySet()) {
                        out.writeString(entry.getKey());
                        out.writeObject(entry.getValue());
                    }
                }

                @Override
                public DeferredMap read(ObjectDataInput in) throws IOException {
                    int size = in.readInt();
                    DeferredMap deferredMap = new DeferredMap(false, size);
                    for (int i = 0; i < size; i++) {
                        deferredMap.put(in.readString(), in.readObject());
                    }
                    return deferredMap;
                }
            };
        }

        @Override
        public boolean isOverwritable() {
            return false;
        }
    }
}
